//
//  RCURLNetRequest.m
//  RCNetRequestProject
//
//  Created by kabu on 2017/7/19.
//  Copyright © 2017年 RC. All rights reserved.
//

#import "RCURLNetRequest.h"

@implementation RCURLNetRequest
+(instancetype)manager{
    RCURLNetRequest *manager = [[self alloc]initWithRequestSerialization:[RCHttpRequestSerialization serializer] responseSerialization:[RCHttpResponseSerialization serializer]];
    
    return manager;
}
-(instancetype)initWithRequestSerialization:(id<RCURLRequestSerialization>)aReqSerialization responseSerialization:(id<RCURLResponseSerialization>)aRepSerializaiton{
    self = [super init];
    if (self) {
        [self setupRequestSerialization:aReqSerialization responseSerialization:aRepSerializaiton];
    }
    return self;
}

- (void)setupRequestSerialization:(id<RCURLRequestSerialization>)aReqSerialization responseSerialization:(id<RCURLResponseSerialization>)aRepSerializaiton{
    self.requestSerialization=aReqSerialization;
    self.responseSerialization=aRepSerializaiton;
}

#pragma mark RCNetRequest
- (id)getWithUrl:(NSString *)url params:(id)params success:(RCNetRequestSuccessBlock)aSuccess failure:(RCNetRequestFailureBlock)aFailure{
    NSError *error;
    NSMutableURLRequest *req = [self requestWithMethod:@"GET" URLString:url parameters:params error:&error];
    NSURLSession *session=[NSURLSession sharedSession];
//    __weak typeof(self) wSelf = self;
    NSURLSessionDataTask *task= [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //
        if (error) {
            if (aFailure) {
                aFailure(error);
            }
        }
        NSError *hasError=nil;
        id result = [self responseObjectForResponseSerialization:response data:data error:&hasError];
        if (hasError) {
            if (aFailure) {
                aFailure(hasError);
            }
        }else{
            if (aSuccess) {
                aSuccess(result);
            }
        }
    }];
    [task resume];
    return task;
}
-(NSString*)logDataToString:(NSData*)data{
    NSString *string=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return string;
}
- (id)postWithUrl:(NSString *)url params:(id)params success:(RCNetRequestSuccessBlock)aSuccess failure:(RCNetRequestFailureBlock)aFailure{
    NSError *error;
    NSMutableURLRequest *req = [self requestWithMethod:@"POST" URLString:url parameters:params error:&error];
    NSURLSession *session=[NSURLSession sharedSession];
//    __weak typeof(self) wSelf = self;
    NSURLSessionDataTask *task= [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //
        if (error) {
            if (aFailure) {
                aFailure(error);
            }
        }
//        NSLog(@"data: %@",data);
//        NSLog(@"data: %@",[self logDataToString:data]);
        NSError *hasError;
        id result = [self responseObjectForResponseSerialization:response data:data error:&hasError];
        if (hasError) {
            if (aFailure) {
                aFailure(hasError);
            }
        }else{
            if (aSuccess) {
                aSuccess(result);
            }
        }
    }];
    [task resume];
    return task;
}
- (id)putWithUrl:(NSString *)url params:(id)params success:(RCNetRequestSuccessBlock)aSuccess failure:(RCNetRequestFailureBlock)aFailure{
    NSError *error;
    NSMutableURLRequest *req = [self requestWithMethod:@"PUT" URLString:url parameters:params error:&error];
    NSURLSession *session=[NSURLSession sharedSession];
//    __weak typeof(self) wSelf = self;
    NSURLSessionDataTask *task= [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //
        if (error) {
            if (aFailure) {
                aFailure(error);
            }
        }
        NSError *hasError;
        id result = [self responseObjectForResponseSerialization:response data:data error:&hasError];
        if (hasError) {
            if (aFailure) {
                aFailure(hasError);
            }
        }else{
            if (aSuccess) {
                aSuccess(result);
            }
        }
    }];
    [task resume];
    return task;
}
- (id)deleteWithUrl:(NSString *)url params:(id)params success:(RCNetRequestSuccessBlock)aSuccess failure:(RCNetRequestFailureBlock)aFailure{
    NSError *error;
    NSMutableURLRequest *req = [self requestWithMethod:@"DELETE" URLString:url parameters:params error:&error];
    NSURLSession *session=[NSURLSession sharedSession];
//    __weak typeof(self) wSelf = self;
    NSURLSessionDataTask *task= [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //
        if (error) {
            if (aFailure) {
                aFailure(error);
            }
        }
        NSError *hasError;
        id result = [self responseObjectForResponseSerialization:response data:data error:&hasError];
        if (hasError) {
            if (aFailure) {
                aFailure(hasError);
            }
        }else{
            if (aSuccess) {
                aSuccess(result);
            }
        }
    }];
    [task resume];
    return task;
}
- (id)downloadWithUrl:(NSString *)url params:(id)params atLocal:(NSURL *)aLocal success:(RCNetRequestSuccessBlock)aSuccess failure:(RCNetRequestFailureBlock)aFailure{
    NSError *error;
    NSMutableURLRequest *req = [self requestWithMethod:nil URLString:url parameters:params error:&error];
    NSURLSession *session=[NSURLSession sharedSession];
    NSURLSessionDownloadTask *task=[session downloadTaskWithRequest:req completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            if (aFailure) {
                aFailure(error);
            }
        }else{
            // 输出下载文件原来的存放目录
            NSLog(@"old loacation %@ \n last %@", location,[[response URL] lastPathComponent]);
            
            
            NSURL *rlocal=aLocal;
            if (!aLocal) {
                NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *defultLocal= [paths objectAtIndex:0];
                rlocal = [NSURL fileURLWithPath:defultLocal];
            }
            // 设置文件的存放目标路径
            NSURL *documentsDirectoryURL = rlocal;
            NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[[response URL] lastPathComponent]];
            // 如果该路径下文件已经存在，就要先将其移除，在移动文件
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {
                [fileManager removeItemAtURL:fileURL error:NULL];
            }
            [fileManager moveItemAtURL:location toURL:fileURL error:NULL];
            if (aSuccess) {
                aSuccess(@{@"local":fileURL});
            }
            
        }
    }];
    [task resume];
    return task;
}
- (id)uploadWithUrl:(NSString *)url params:(id)params withLocal:(NSURL *)wLocal success:(RCNetRequestSuccessBlock)aSuccess failure:(RCNetRequestFailureBlock)aFailure{
    NSError *error;
    NSMutableURLRequest *req = [self requestWithMethod:@"POST" URLString:url parameters:params error:&error];
    NSURLSession *session=[NSURLSession sharedSession];
//    __weak typeof(self) wSelf = self;
    NSURLSessionDataTask *task= [session uploadTaskWithRequest:req fromFile:wLocal completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //
        if (error) {
            if (aFailure) {
                aFailure(error);
            }
        }
        NSError *hasError;
        id result = [self responseObjectForResponseSerialization:response data:data error:&hasError];
        if (hasError) {
            if (aFailure) {
                aFailure(hasError);
            }
        }else{
            if (aSuccess) {
                aSuccess(result);
            }
        }
    }];
    [task resume];
    return task;
}
-(id)postWithUrl:(NSString *)url params:(id)params formData:(NSData *)aFormData mimeType:(NSString *)mimeType fileName:(NSString *)fileName name:(NSString *)name success:(RCNetRequestSuccessBlock)aSuccess failure:(RCNetRequestFailureBlock)aFailure{
//    NSError *error;
    RCHttpRequestSerialization*reqSerialization =  self.requestSerialization;
    NSMutableURLRequest *req = [reqSerialization requestWithFormData:aFormData urlString:url parameters:params fileName:fileName name:name mimeType:mimeType];
    NSURLSession *session=[NSURLSession sharedSession];
    NSURLSessionDataTask *task= [session uploadTaskWithRequest:req fromData:req.HTTPBody completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //
        if (error) {
            if (aFailure) {
                aFailure(error);
            }
        }
        NSError *hasError;
        id result = [self responseObjectForResponseSerialization:response data:data error:&hasError];
        if (hasError) {
            if (aFailure) {
                aFailure(hasError);
            }
        }else{
            if (aSuccess) {
                aSuccess(result);
            }
        }
    }];
    [task resume];
    return task;
}
@end
